layui.use(['tree','table','treeGrid','layer','jquery'],function(){

    var $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var form=layui.form;

    var tempFacilityId="";
    //列表数据
    var option = {
        elem: '#tableList',
        url : '/admin/facility/getFacilityList',
        cellMinWidth : 95,
        page : true,
        height : "full-125",
        limits : [10,15,20,25],
        limit : 15,
        id : "listTable",
        loading:true,
        cols : [[
            {type: "checkbox", fixed:"left", width:50},
            {field: 'categoryName', title: '类别名', align:'center',minWidth:100,templet:function (d){
                    var name = null;
                    $.ajax({
                        url:"/admin/facilityCategory/getFacilityCategory?facilityCategoryId="+d.categoryId,
                        type:'GET',
                        async:false,
                        success:function (data){
                            name = data.name;
                        }
                    });
                    return name;

            }},
            {field: 'facilityId', title: '仪器编号', align:'center',minWidth:120},
            {field: 'facilityName', title: '仪器名称', minWidth:160, align:'center'},
            {field: 'storageId', title: '存放位置', align:'center',minWidth:150,templet:function (d){
                    var name = null;
                    $.ajax({
                        url:"/admin/storage/getStorage?StorageId="+d.storageId,
                        type:'GET',
                        async:false,
                        success:function (data){
                            name = data.name;
                        }
                    });
                    return name;
                }},
            {field: 'facilityNo', title: '品牌型号', minWidth:120, align:"center"},
            {field: 'afterSaleMobile', title: '售后电话',minWidth:120, align:'center'},
            {field: 'buyDate', title: '购买时间', minWidth:200, align:'center',sort:true, templet:function(d){
                    //处理时间
                    var date = new Date(d.buyDate);
                    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+ " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                }},
            // {field: 'status', title: '仪器状态',minWidth:120, align:'center',sort:true,templet:function (d) {
            //         return d.status == 0? "正常": "报废";
            //     }},
            {field: 'status', title: '仪器状态',minWidth:120, align:'center',sort:true, templet: '#switchTpl', unresize: true},
            {field: '88',title: '操作', minWidth:175, templet:'#tableListBar',fixed:"right",align:"center"}
        ]],
        done: function(res, curr, count) {
             // var data;
             //    table.on('rowDouble(tableList)', function(obj) {
             //        data = obj.data;
             //        layui.layer.open({
             //            title: '在线调试'
             //            ,type:2
             //            ,resize:false
             //            ,area:['600px','630px']
             //            ,shadeClose:true
             //            ,content: "facilityDetails.jsp?id=" + data.facilityId
             //        });
             //    })
           // })

        }
    };

    //设备列表
    var tableIns = table.render(option);

    // table.on('row(tableList)', function(obj){
    //     tempFacilityId=obj.data.facilityId;
    //     console.log(obj)
    // });

    //监听性别操作
    form.on('switch(sexDemo)', function(d){
        //修改
        if(this.value==0)
            this.value=1;
        else
            this.value=0;
        $.post("/admin/facility/edit",{
            facilityId:$(d.elem).data('id'),
            status:this.value
        },function(res){
            if(res.code==200) {
                top.layer.msg("修改成功！");
                return true;
            }else {
                top.layer.msg(res.message);
                return false;
            }

        })

        // tableIns.reload();
        // layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
    });

    //场景数据
    var height = $(document).height();
    $(".orgbox").css('height',(height - 40) + "px");
    $(window).on("resize",function () {
        $(".orgbox").css('height',(height - 40) + "px");
    });
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            option.url = '/admin/facility/getFacilityListByCate';
            option.where = {categoryId: item.id};
            table.render(option);
        },
        nodes:null
    };

    $.get('/admin/facilityCategory/menu',function(data) {
        treeData.nodes = data.data;
        layui.tree(treeData);
    });



    //搜索设备信息
    const IntervalId = setInterval(() => {
        if ($(".addNews_btn").length != 0) {
    $(".search_btn").on("click",function(){
        var searchKey = $(".searchVal").val();
        if(searchKey != ''){
            option.url = '/admin/facility/search';
            option.method = 'post';
            option.where = {keyword: searchKey};
            table.render(option);
            //权限时候添加类名  layui-btn-disabled


        }else{
            layer.msg("请输入搜索的内容");
        }
    });


    //添加设备
    $(".addNews_btn").click(function(){
        var index = layui.layer.open({
            title : "添加产品",
            type : 2,
            content : "facilityAdd.jsp",
            area: ['100%','100%'],
            success : function(){
                //这里可以有写成功后的其他操作
                setTimeout(function(){
                    layui.layer.tips('点击此处返回记录列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(index);
        });
    });

        //批量添加addExcel
        layui.use('upload', function(){
            var upload = layui.upload;
            //执行实例
            var uploadInst = upload.render({
                elem: '#addConsumableExcel' //绑定元素
                ,field: 'uploadFile'
                ,url: '/admin/facility/addFacilityExcel' //上传接口
                ,acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel.sheet.macroEnabled.12'
                ,accept:'file'
                ,done: function(res) {
                    //上传完毕回调
                    layer.open({
                        content: '共需要添加' + res.count + '条记录'
                        , btn: ['确认添加', '取消']
                        , yes: function (index, layero) {
                            console.log(res.data)
                            //按钮【按钮一】的回调
                            var a = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.8});
                            top.layer.close(a);
                            top.layer.msg("数据添加成功！");
                            //刷新页面
                            tableIns.reload();
                            layer.close(index)
                        }
                        , btn2: function (index, layero) {
                            console.log(res.data)
                            $.get("/admin/facility/batchDelete", {
                                ids: res.data  //将需要删除的newsId作为参数传入
                            }, function (data) {
                                if (data.code == 200) {
                                } else {
                                    layer.msg("数据添加异常！请重试");
                                }
                                layer.close(index);
                            })
                        }
                    })
                }
            });
        });



    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('listTable'),//此处的id为table数据格式中的id
            data = checkStatus.data,
            idArr = [];
        if(data.length > 0) {
            for (var i in data) {
                idArr.push(data[i].facilityId);
            }
            layer.confirm('确定删除选中的产品记录？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/admin/facility/batchdelete",{
                    ids : idArr  //将需要删除的newsId作为参数传入
                },function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                })

            })
        }else{
            layer.msg("请选择需要删除的记录");
        }
    });
        clearInterval(IntervalId);
    }
},0);
    //列表操作
    table.on('tool(tableList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit' && $('#edit').hasClass('layui-btn-disabled') === false){ //编辑
            var index = layui.layer.open({
                title : "修改产品信息",
                type : 2,
                content : "/admin/views/facility/facilityEdit.jsp?id=" + data.facilityId,
                area: ['100%',$(document).height() - 30 + 'px'],
                success : function(){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
            layui.layer.full(index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize",function(){
                layui.layer.full(index);
            });
        }
        else if(layEvent === 'del' && $('#del').hasClass('layui-btn-disabled') === false){ //删除
            layer.confirm('确定删除此记录吗？',{icon:3, title:'提示信息'},function(index){
                $.get("/admin/facility/delete?id=" + data.facilityId,function(data){
                    if (data.code == 200) {
                        layer.msg("删除成功！");
                    } else {
                        layer.msg("删除失败，请重试！");
                    }
                    tableIns.reload();
                    layer.close(index);
                });
            });
        }
    });

});